<script setup>
import ListHeader from '@/components/ListHeader.vue';
import { getCategoryListAPI, createCategoryAPI, updateCategoryAPI, updateCategoryStatusAPI, deleteCategoryAPI } from '@/api/category';
import { useInitTable, useInitForm } from '@/composables/useCommon';
import { ref } from 'vue'
import FormDrawer from '@/components/FormDrawer.vue';
import GoodsDrawer from './components/GoodsDrawer.vue';
const {
  loading,
  getData,
  tableData,
  handleStatusChange,
  handleDelete
} = useInitTable(
  {
    getList: getCategoryListAPI,
    onGetListSuccess: (res) => {
      tableData.value = res.map(o => {
        o.goodsDrawerLoading = false
        return o
      })
    },
    delete: deleteCategoryAPI,
    updateStatus: updateCategoryStatusAPI
  }
)

const {
  form,
  rules,
  formDrawerRef,
  formRef,
  drawerTitle,
  handleEdit,
  handleSubmit,
  handleCreate,
} = useInitForm(
  {
    form: {
      name: ''
    },
    rules: {
    },
    getData,
    update: updateCategoryAPI,
    add: createCategoryAPI
  }
)

const goodsDrawerRef = ref(null)
const openGoodsDrawer = (data) => {
  goodsDrawerRef.value.open(data)
}
</script>
<template>
  <el-card shadow="never" class="border-0">
    <ListHeader @create="handleCreate" @refresh="getData"></ListHeader>
    <el-tree :expand-on-click-node="false" :data="tableData" :props="{ label: 'name', children: 'child' }"
      v-loading="loading" node-key="id">
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <span>{{ data.name }}</span>
          <div class="ml-auto">
            <el-button :loading="data.goodsDrawerLoading" text type="primary" size="small"
              @click="openGoodsDrawer(data)">推荐商品</el-button>
            <el-switch :model-value="data.status" :active-value="1" :inactive-value="0"
              @change="handleStatusChange($event, data)"></el-switch>
            <el-button text type="primary" size="small" @click.stop="handleEdit(data)">修改</el-button>
            <el-popconfirm @confirm="handleDelete(data.id)" confirm-button-text="确认" cancel-button-text="取消"
              title="你确定要删除吗?">
              <template #reference>
                <el-button text type="primary" size="small">删除</el-button>

              </template>
            </el-popconfirm>
          </div>
        </div>
      </template>
    </el-tree>
    <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="分类名称"></el-input>
        </el-form-item>
      </el-form>
    </FormDrawer>
    <GoodsDrawer ref="goodsDrawerRef"></GoodsDrawer>
  </el-card>
</template>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

:deep(.el-tree-node__content) {
  padding: 20px 0;
}
</style>